<?php
/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */

namespace App\Repositories;


use App\Interfaces\DistributeInterface;
use App\Interfaces\UserInterface;
use App\Notifications\UserNotification;
use App\Notifications\WechatNotification;
use App\User;
use Carbon\Carbon;

class DistributeRepository implements DistributeInterface
{
    protected  $user;
    public function __construct()
    {
        $this->user=new UserRepository();
    }

    /**
     * @param User $user 需要绑定的user模型
     * @param $leaderId 上级领导 需要绑定团队
     * @return mixed
     */
    public function bindDistribute(User $user,$leaderId){
        $leader=User::find($leaderId);
        if($user->id==$leaderId){
            return false;
        }
        if(!$user->team_leader){
            if(!empty($leader->team_path)){//如果存在节点树
                $team_path=$leader->team_path;
                array_shift($team_path);
                $team_path=implode(',',$leader->team_path);
                $team_path=str_replace('0,','',$team_path);
                $user->team_path='0,'.$leaderId.','.$team_path;

            }else{
                $user->team_path='0,'.$leaderId;
            }
            $user->team_leader=$leaderId;
            $user->leader_time=Carbon::now();
            $user->save();
            //直推人数+1
            \DB::table('users')->where('id',$leaderId)->increment('promotion_number',1);
            //推送消息
            $leader->notify(new UserNotification([
                'template_id' => 'EICSe0rbFDPr6922Ydffzq4Z-2MFsr5amMJCYLRqUkw',
                'url' => config('app.url'),
                'data' => [
                    'first' => '您有新粉丝加入',
                    'keyword1' => $user->name,
                    'keyword2' => $user->id,
                    'keyword3' => $user->updated_at,
                    'remark' => '去和TA打招呼吧',

                ]

            ]));
            //检测上级会员等级
            if($leader)
            $this->user->checkTeamLeavel($leader);
            return $leader;
        }
    }

}